<script setup lang="ts">
import { ref, watch } from "vue";

import type { FormItemProps } from "../utils/types.ts";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { message } from "@/utils/message";

const props = defineProps<FormItemProps>();
const emit = defineEmits(["success"]);

const formRef = ref();
const form = ref<{
  id?: number;
  deviceName?: string;
  correlatedDevice?: string;
  status?: number;
  [key: string]: any;
}>({});

// 表单规则
const rules = {
  deviceName: [
    {
      required: true,
      message: "请输入设备名称",
      trigger: "blur"
    }
  ],
  correlatedDevice: [
    {
      required: true,
      message: "请输入关联设备",
      trigger: "blur"
    }
  ]
};

watch(
  () => props.form,
  val => {
    form.value = { ...val };
  },
  {
    immediate: true
  }
);

function submitForm() {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      const params = { ...form.value };
      const url =
        props.type === "新增"
          ? "index.php/device/deviceCorrelated/deviceCorrelated_add"
          : "index.php/device/deviceCorrelated/deviceCorrelated_update";

      http
        .post(changeHttpLink(url), {
          data: params
        })
        .then((res: any) => {
          if (res.Success) {
            message(`${props.type}设备关联成功`, { type: "success" });
            emit("success");
          } else {
            message(res.Message, { type: "error" });
          }
        })
        .catch(err => {
          message(err.message, { type: "error" });
        });
    }
  });
}
</script>

<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="100px"
    class="w-full"
  >
    <el-form-item label="设备名称" prop="deviceName">
      <el-input
        v-model="form.deviceName"
        placeholder="请输入设备名称"
        :disabled="props.type === '修改'"
      />
    </el-form-item>
    <el-form-item label="关联设备" prop="correlatedDevice">
      <el-input v-model="form.correlatedDevice" placeholder="请输入关联设备" />
    </el-form-item>
    <el-form-item label="状态" prop="status">
      <el-select v-model="form.status" placeholder="请选择状态">
        <el-option label="已启用" value="1" />
        <el-option label="已停用" value="0" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm"> 确定 </el-button>
      <el-button @click="formRef.value.resetFields()"> 重置 </el-button>
    </el-form-item>
  </el-form>
</template>
